<?php
/***
 * ActionLeaf (www.actionleaf.com / actionleaf.googlecode.com) PHP Framework
 * Copyright (c) 2008, Wess D. Cope <wess@wattz.net>
 * All rights reserved.								
 * 													
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:                   
 * 																				
 * 	* Redistributions of source code must retain the above copyright notice,	
 * 	this list of conditions and the following disclaimer.						
 * 																				
 * 	* Redistributions in binary form must reproduce the above copyright notice, 
 * 	this list of conditions and the following disclaimer in the documentation   
 * 	and/or other materials provided with the distribution. 						
 * 																				
 * 	* Neither the name of the <ORGANIZATION> nor the names of its contributors may
 * 	be used to endorse or promote products derived from this software without     
 * 	specific prior written permission.											
 * 																				
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 	 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES  
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 	 
 * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 		 
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 	 
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 	 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 	 
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 	 
 * DAMAGE.																				 
 **/

/**
 * Foundation.ALDbConnection
 * Create and manage ActionLeaf database connections and 
 * connection requests... <incomplete/>
 */

class ALDbConnection
{

	private static $instance;

	private $connections;
	private $connectionPool;

	private function __construct()
	{

		$this->connections = ALFormatParser::yaml(ROOT_DIR . '/system/conf/database.conf');

	}
	
	/**
	 * Connect to a database and store the connection in pool.
	 *
	 * @param	string
	 *
	 * @return	bool
	 **/
	private function connect($connName) 
	{

		if (isset($this->connections[$connName])) {
			
			$connInfo=$this->connections[$connName];
			switch($connInfo['type'])
			{

				case "mysql":
					try {
						
						$port = isset($connInfo['port']) ? $connInfo['port'] : 3306;
						$socket = isset($connInfo['sock']) ? $connInfo['sock'] : null;
						$this->connectionPool[$connName] = new ALMySQLDriver($connInfo['host'], $connInfo['database'], $connInfo['username'], $connInfo['password'], $port, $socket);
						return true;
					} catch(PDOException $e) {
						if (isset($connInfo['dieOnFail'])&&$connInfo['dieOnFail']===true)
							die("DB Connection error: " . $e->getMessage());
					}
				break;

				case "sqlite":
					try {
						$this->connectionPool[$connName] = new ALSQLiteDriver($connInfo['path'], $connInfo['version'], $connInfo['inMemory']);
						return true;
					} catch(PDOException $e) {
						if (isset($connInfo['dieOnFail'])&&$connInfo['dieOnFail']===true)
							die("DB Connection error: " . $e->getMessage());
					}
				break;

				case "postgresql":
					try {
						$this->connectionPool[$connName] = new ALPostgreSQLDriver($connInfo['host'], $connInfo['database'], $connInfo['username'], $connInfo['password']);
						return true;
					} catch(PDOException $e) {
						if (isset($connInfo['dieOnFail'])&&$connInfo['dieOnFail']===true)
							die("DB Connection error: " . $e->getMessage());
					}
				break;

				default:
					die("DB Connection error: Invalid database type '{$connInfo['type']}'");
				break;

			}

		} else {
			die("DB Connection error: {$connName} does not exist in the database.conf");
		}

	}
	
	/**
	 * Setup insance of object if it doesn't exist 
	 **/
	private static function setupInstance()
	{

		// Create instace it doesn't exist
		if (empty(self::$instance))
			self::$instance = new ALDbConnection;

	}

	/**
	 * Return PDO object
	 *
	 * @param	string
	 *
	 * @return	object
	 **/
	public static function getConnection($connName)
	{

		self::setupInstance();

		if (isset(self::$instance->connectionPool[$connName])) {
			// Return connection since it has already been created
			return self::$instance->connectionPool[$connName];
		} else if (self::$instance->connect($connName)) {
			// Build Connection and return it
			return self::$instance->connectionPool[$connName];
		} else {
			// Failed to create
			die("DB Connection error: {$connName} failed to connect when trying to get accessed");
		}

	}

	/**
	 * Return connection database type
	 *
	 * @param	string
	 *
	 * @return	string
	 **/
	public static function getConnDBType($connName)
	{

		self::setupInstance();
		
		return self::$instance->connections[$connName]['type'];

	}

}